// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "FLTSavePhotoDelegate.h"
#import "FLTSavePhotoDelegate_Test.h"
#import <CoreMotion/CoreMotion.h>

@interface FLTSavePhotoDelegate ()
/// The file path for the captured photo.
@property(readonly, nonatomic) NSString *path;
/// The queue on which captured photos are written to disk.
@property(readonly, nonatomic) dispatch_queue_t ioQueue;

@property(assign, nonatomic) FLTResolutionPreset resolutionPreset;

@end

@implementation FLTSavePhotoDelegate

- (instancetype)initWithPath:(NSString *)path
                     ioQueue:(dispatch_queue_t)ioQueue
            resolutionPreset:(FLTResolutionPreset)resolutionPreset
           completionHandler:(FLTSavePhotoDelegateCompletionHandler)completionHandler {
  self = [super init];
  NSAssert(self, @"super init cannot be nil");
  _path = path;
  _ioQueue = ioQueue;
  _completionHandler = completionHandler;
_resolutionPreset = resolutionPreset;
  return self;
}

- (void)handlePhotoCaptureResultWithError:(NSError *)error
                        photoDataProvider:(NSData * (^)(void))photoDataProvider {
  if (error) {
    self.completionHandler(nil, error);
    return;
  }
  __weak typeof(self) weakSelf = self;
  dispatch_async(self.ioQueue, ^{
    typeof(self) strongSelf = weakSelf;
    if (!strongSelf) return;
      NSData *data = photoDataProvider();
      
      NSError *ioError;
      if ([[self cropImageWithData:data] writeToFile:strongSelf.path options:NSDataWritingAtomic error:&ioError]) {
        strongSelf.completionHandler(self.path, nil);
      } else {
        strongSelf.completionHandler(nil, ioError);
      }
//      UIImageWriteToSavedPhotosAlbum([UIImage imageWithData:[self cropImageWithData:data]], self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
  });
}

- (NSData *)cropImageWithData:(NSData *)data {
    if(_resolutionPreset != FLTResolutionPresetR11) return data;
    /// 原图
    UIImage *image =  [UIImage imageWithData:data];
    ///裁剪尺寸
    CGRect rect = CGRectMake(0, 50, image.size.width, image.size.width);
    // 检查裁剪区域是否在图像范围内
    if (CGRectGetMaxX(rect) > image.size.width || CGRectGetMaxY(rect) > image.size.height) {
        NSLog(@"裁剪区域超出图像范围");
        return data;
    }

    // 开始图像上下文
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, image.scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // 调整裁剪区域以考虑图像方向
//    CGAffineTransform transform = CGAffineTransformIdentity;
//    switch (image.imageOrientation) {
//        case UIImageOrientationLeft:
//            transform = CGAffineTransformTranslate(transform, rect.size.width, 0);
//            transform = CGAffineTransformRotate(transform, M_PI_2);
//            break;
//        case UIImageOrientationRight:
//            transform = CGAffineTransformTranslate(transform, 0, rect.size.height);
//            transform = CGAffineTransformRotate(transform, -M_PI_2);
//            break;
//        case UIImageOrientationDown:
//            transform = CGAffineTransformTranslate(transform, rect.size.width, rect.size.height);
//            transform = CGAffineTransformRotate(transform, M_PI);
//            break;
//        default:
//            break;
//    }
//    CGContextConcatCTM(context, transform);
    
    // 将图像绘制到上下文中
    [image drawInRect:CGRectMake(-rect.origin.x, -rect.origin.y, image.size.width, image.size.height)];
    
    // 获取裁剪后的图像
    UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return UIImageJPEGRepresentation(croppedImage, 1.0);
}

//- (void)handlePhotoCaptureResultWithError:(NSError *)error
//                        photoDataProvider:(NSData * (^)(void))photoDataProvider {
//  if (error) {
//    self.completionHandler(nil, error);
//    return;
//  }
//  __weak typeof(self) weakSelf = self;
//  dispatch_async(self.ioQueue, ^{
//    typeof(self) strongSelf = weakSelf;
//    if (!strongSelf) return;
//      
//    NSData *data = photoDataProvider();
//      UIImage *capturedImage = [UIImage imageWithData:data];
//
//      if ([self.motionManager isDeviceMotionAvailable]) {
//          [self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
//              if (error) {
//                  NSLog(@"Error reading device motion: %@", error.localizedDescription);
//                  return;
//              }
//              
//              double x = motion.gravity.x;
//              double y = motion.gravity.y;
//              double z = motion.gravity.z;
//              
//              // 根据重力方向判断手机的倾斜方向
//              NSString *orientation = [self orientationFromGravityX:x y:y z:z];
//              if(self.orientation == 1) {
//                  if([orientation isEqualToString:@"Portrait"] || [orientation isEqualToString:@"PortraitUpsideDown"]) {
//                      orientation = @"LandscapeRight";
//                  }
//              } else if (self.orientation == 2){
//                  orientation = @"Portrait";
//              }
//              
//              // 根据手机的倾斜方向修正图像
//              UIImage *correctedImage = [self correctAndRotateImage:capturedImage forOrientation:orientation];
//              
//              // 将图像数据写入文件
//              NSData *imageData = UIImageJPEGRepresentation(correctedImage, 1.0);
//              
//            NSError *ioError;
//            if ([imageData writeToFile:strongSelf.path options:NSDataWritingAtomic error:&ioError]) {
//              strongSelf.completionHandler(self.path, nil);
//            } else {
//              strongSelf.completionHandler(nil, ioError);
//            }
//              [self.motionManager stopDeviceMotionUpdates];
//          }];
//      } else {
//          NSLog(@"Device motion is not available");
//      }
//  });
//}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if (error) {
        NSLog(@"保存图片失败：%@", error.localizedDescription);
    } else {
        NSLog(@"图片保存成功！");
    }
}

- (void)dealloc {


}


/// 保存图片
- (void)captureOutput:(AVCapturePhotoOutput *)output
    didFinishProcessingPhoto:(AVCapturePhoto *)photo
                       error:(NSError *)error {
  [self handlePhotoCaptureResultWithError:error
                        photoDataProvider:^NSData * {
                          return [photo fileDataRepresentation];
                        }];
}


// 根据重力方向判断手机的倾斜方向
- (NSString *)orientationFromGravityX:(double)x y:(double)y z:(double)z {
    if (fabs(y) >= fabs(x)) {
        return (y >= 0) ? @"PortraitUpsideDown" : @"Portrait";
    } else {
        return (x >= 0) ? @"LandscapeRight" : @"LandscapeLeft";
    }
}

// 根据手机的倾斜方向修正图像
- (UIImage *)correctAndRotateImage:(UIImage *)image forOrientation:(NSString *)orientation {
    if ([orientation isEqualToString:@"Portrait"]) {
        return image;
    } else if ([orientation isEqualToString:@"PortraitUpsideDown"]) {
        return [self rotateImage:image byAngle:M_PI];
    } else if ([orientation isEqualToString:@"LandscapeLeft"]) {
        return [self rotateImage:image byAngle:-M_PI_2];
    } else if ([orientation isEqualToString:@"LandscapeRight"]) {
        return [self rotateImage:image byAngle:M_PI_2];
    }
    return image;
}


- (UIImage *)rotateImage:(UIImage *)image byAngle:(CGFloat)angle {
    CGSize imageSize = image.size;
    CGRect rotatedRect = CGRectApplyAffineTransform(CGRectMake(0, 0, imageSize.width, imageSize.height), CGAffineTransformMakeRotation(angle));
    CGSize rotatedSize = rotatedRect.size;

    UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:rotatedSize];
    UIImage *rotatedImage = [renderer imageWithActions:^(UIGraphicsImageRendererContext * _Nonnull context) {
        CGContextRef ctx = UIGraphicsGetCurrentContext();

        // 将坐标系移动到旋转后的图片中心
        CGContextTranslateCTM(ctx, rotatedSize.width / 2, rotatedSize.height / 2);

        // 旋转图形上下文
        CGContextRotateCTM(ctx, angle);

        // 绘制图像到旋转后的图形上下文
        [image drawInRect:CGRectMake(-imageSize.width / 2, -imageSize.height / 2, imageSize.width, imageSize.height)];
    }];

    return rotatedImage;
}
@end
